package com.github.hiling.gateway.filter;

import com.github.hiling.common.utils.StringUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * Author by hiling, Date on 10/15/2018.
 * @author hiling
 */
@Slf4j
@Getter
@Setter
@Component
@ConfigurationProperties("link")
public class UriRedirectFilter implements GlobalFilter, Ordered {

    @Override
    public int getOrder() {
        return 0;
    }

    private Map<String, String> redirect;

    /**
     * 可以使用自带的RedirectTo实现
     * spring:
     *   cloud:
     *     gateway:
     *       routes:
     *       - id: prefixpath_route
     *         uri: http://example.org
     *         filters:
     *         - RedirectTo=302, http://acme.org
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

//        final String serviceId = (String) RequestContext.getCurrentContext().get("proxy");
        //todo: 此处需要获取 serviceId
        final String serviceId = "test";

        if ("link".equals(serviceId)){
            ServerHttpRequest serverHttpRequest = exchange.getRequest();

            //url格式必须为 /link/key
            String mapKey = serverHttpRequest.getPath().value().split("/")[2].toLowerCase();
            log.debug("Local URI:{}",mapKey);
            String path = redirect.get(mapKey);
            log.debug("Remote URI:{}",path);
            if (StringUtils.isNoneEmpty(path)) {

                // 重定向到新地址
                ServerHttpResponse serverHttpResponse = exchange.getResponse();
                serverHttpResponse.getHeaders().set(HttpHeaders.LOCATION,path);
                serverHttpResponse.setStatusCode(HttpStatus.SEE_OTHER);
                return serverHttpResponse.setComplete();
            }
        }

        return chain.filter(exchange);
    }
}